package com.li.blog.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.li.blog.common.dto.CommentDto;
import com.li.blog.common.lang.Result;
import com.li.blog.entity.Blog;
import com.li.blog.entity.Comments;
import com.li.blog.entity.Preview;
import com.li.blog.entity.User;
import com.li.blog.mapper.CommentsMapper;
import com.li.blog.mapper.PreviewMapper;
import com.li.blog.mapper.UserMapper;
import com.li.blog.service.BlogService;
import com.li.blog.service.CommentsService;
import com.li.blog.service.PreviewService;
import com.li.blog.service.UserService;
import com.li.blog.utils.ShiroUtil;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Liyangjing
 * @since 2021-11-23
 */
@RestController
public class BlogController {


    @Autowired
    BlogService blogService;

    @Autowired
    CommentsService commentsService;
    @Autowired
    PreviewService previewService;
    @Autowired
    CommentsMapper commentsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserService userService;

    /**
     * 返回所有博客
     * @param currentPage
     * @return
     */
    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page page = new Page(currentPage, 5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));

        return Result.succ(pageData);
    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已被删除");

        return Result.succ(blog);
    }
    @RequiresAuthentication
    @PostMapping("/blog/delete/{id}")
    public Result delete(@PathVariable(name = "id") Long id){
        boolean b = blogService.removeById(id);
        if(b){
            return Result.succ("成功删除");
        }
        return Result.fail("删除失败");
    }
    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {

//        Assert.isTrue(false, "公开版不能任意编辑！");

        Blog temp = null;
        if(blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            // 只能编辑自己的文章
            System.out.println(ShiroUtil.getProfile().getId());
            Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有权限编辑");
        } else {
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }

        BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
        blogService.saveOrUpdate(temp);

        return Result.succ(null);
    }
    @PostMapping("/blog/good/{id}")
    public Result good(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        if(blog!=null){
            int i = blog.getGood();
            i=i+1;
            blog.setGood(i);
            blogService.updateById(blog);
            return Result.succ("点赞成功");
        }
        return Result.fail("未找到博客，点赞失败");
    }
    @PostMapping("/blog/bad/{id}")
    public Result bad(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        if(blog!=null){
            int i = blog.getBad();
            i=i+1;
            blog.setBad(i);
            blogService.updateById(blog);
            return Result.succ("bad成功");
        }
        return Result.fail("未找到博客，点赞失败");
    }
    @GetMapping("/blog/getGood/{id}")
    public Result getGood(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        if(blog!=null){
            return Result.succ(blog.getGood());
        }
        return Result.fail("未找到博客，获取点赞");
    }
    @GetMapping("/blog/getBad/{id}")
    public Result getBad(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        if(blog!=null){
            return Result.succ(blog.getBad());
        }
        return Result.fail("未找到博客，获取拉黑");
    }
    /**
     * 返回所有评论
     */
    @GetMapping("/comments/preview/{id}")
    public Result getPreview(@PathVariable(name = "id") Long id){
        QueryWrapper<Preview> wrapper = new QueryWrapper<>();
        wrapper.eq("blog_id", id)
                .select("id");
        List<Preview> previews = previewService.list(wrapper);
        List<Long> list2 = new ArrayList<>();
        for (Preview preview : previews) {
            list2.add(preview.getId());
        }
        /**
         * 获取所有评论
         */
        QueryWrapper<Comments> commentswrapper = new QueryWrapper<>();
        System.out.println("========"+list2);
        if(list2.isEmpty()){
            return Result.succ(null);
        }
        commentswrapper.in("id", list2);
        List<Comments> comments = commentsService.list(commentswrapper);

        for (Comments comment : comments) {
            User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, comment.getUsername()));
            if (StrUtil.isNotBlank(one.getAvatar())) {
                comment.setAvatar(one.getAvatar());
                comment.setEmail(one.getEmail());
            } else {
                // 默认一个头像
                comment.setAvatar("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png");
            }
        }
    return Result.succ(comments);
    }
    /**
     *     添加评论
     */
    @PostMapping("/comments/addpreview")
    public Result addComment(@RequestBody @Validated CommentDto commentDto){
        Comments comments = new Comments();
        comments.setUsername(commentDto.getUsername());
        comments.setContent(commentDto.getContent());
        comments.setTime(LocalDateTime.now());
        comments.setForeignId(new Long(0));
        commentsService.save(comments);
        QueryWrapper<Comments> wrapper = new QueryWrapper<>();
        wrapper.eq("username",commentDto.getUsername())
                .eq("content",commentDto.getContent())
                .select("id");
        Comments one = commentsService.getOne(wrapper);
        if(one!=null){
            System.out.println(one);
            Preview preview = new Preview();
            preview.setId(one.getId());
            preview.setBlogId(commentDto.getBlogId());
            previewService.save(preview);
            return Result.succ("发布评论成功");
        }
        return Result.fail("发布评论失败");
    }
    /**
     * 删除评论
     */
    @PostMapping("/comments/delete/{id}")
    public Result deleteComment(@PathVariable(name = "id") Long id){
        if(id!=null)
        {
            commentsService.removeById(id);
            previewService.removeById(id);
            return Result.succ("删除成功");
        }
        return Result.fail("删除失败");
    }

}
